// 实现这个项目的构建任务
const { src, dest, parallel, series, task, watch } = require('gulp');
const del = require('del');
const sass = require('gulp-sass')(require('sass'));
const loadPlugins = require('gulp-load-plugins');
const plugins = loadPlugins();
const browserSync = require('browser-sync')
const eslint = require('gulp-eslint');
const bs = browserSync.create()
const data = {
    menus: [
        {
            name: 'Home',
            link: 'index.html'
        },
        {
            name: 'About',
            link: 'about.html'
        },
    ],
    pkg: require('./package.json'),
    date: new Date()
}

const clean = () => {
    return del(['dist', 'temp'])
}

const style = () => {
    return src('src/assets/styles/**.scss', { base: 'src' })
        .pipe(sass())
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}

const script = () => {
    return src('src/assets/scripts/**.js', { base: 'src' })
        .pipe(plugins.babel())
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}

const page = () => {
    return src('src/**.html')
        .pipe(plugins.swig({ data, default: { cache: false } }))
        .pipe(dest('temp'))
        .pipe(bs.reload({ stream: true }))
}

const image = () => {
    return src('src/images/**', { base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('temp'))
}

const font = () => {
    return src('src/assets/fonts/**', { base: 'src' })
        .pipe(plugins.imagemin())
        .pipe(dest('dist'))
}

const lint = () => {
    return src('src/assets/scripts/*.js', { base: 'src' })
        .pipe(eslint({
            rules: {
                'strict': 2
            },
            globals: [
                'jQuery',
                '$'
            ],
            envs: [
                'browser'
            ]
        }))
        .pipe(eslint.format())
        .pipe(eslint.failAfterError())
        // .pipe(plugins.eslint.format())
        // .pipe(plugins.eslint.failAfterError())
}
const compile = parallel(style, script, page)
const extra = () => {
    return src('public/**', { base: 'public' })
        .pipe(dest('dist'))
}
const server = () => {
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/scripts/*.js', script)
    watch('src/*.html', page)
    watch([
        'src/assets/images/**',
        'src/assets/fonts/**',
        'public/**'
    ], bs.reload)

    bs.init({
        notify: false,
        port: 8000,
        server: {
            baseDir: ['temp', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}


const useref = () => {
    return src('temp/*.html', { base: 'temp' })
        // gulp-useref 插件会将多个路径不同的文件拼接成一个文件
        .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
        .pipe(plugins.if(/\.js$/, plugins.uglify()))
        .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
        .pipe(plugins.if(/\.html$/, plugins.htmlmin({
            collapseWhitespace: true,
            minifyCSS: true,
            minifyJS: true
        })))
        .pipe(dest('dist'))
}

const serve = series(compile, server)

const build = series(clean,
    parallel(series(compile, useref), image, font, extra))

const GulpSSH = require('gulp-ssh')

// eslint-disable-next-line @typescript-eslint/camelcase
const { APP_ENV, npm_package_name } = process.env;
const isProduct = APP_ENV === 'production';

// 需要上传到服务器的路径
// eslint-disable-next-line @typescript-eslint/camelcase
const remotePath = `/home/public/docker/main/${npm_package_name}`
const config = {
    ssh: { // 正式
        host: isProduct ? '' : '192.168.31.227',
        port: isProduct ? 22 : 8822,
        username: 'root',
        password: isProduct ? '' : 'a1234567',
    },
    remotePath,
    commands: [
        // 删除现有文件
        `rm -rf ${remotePath}`,
    ],
}
const gulpSSH = new GulpSSH({
    ignoreErrors: false,
    sshConfig: config.ssh,
})
/**
 * 上传前先删除服务器上现有文件...
 */
task('execSSH', () => {
    console.log('删除服务器上现有文件...')
    return gulpSSH.shell(config.commands, { filePath: 'commands.log' })
        .pipe(gulp.dest('logs'))
})
/**
 * 上传文件到服务器
 */

task('deploy', series('execSSH', done => {
    console.log('2s后开始上传文件到服务器...')
    setTimeout(() => {
        // eslint-disable-next-line @typescript-eslint/camelcase
        src(`./${npm_package_name}/**`)
            .pipe(gulpSSH.dest(config.remotePath))
        console.log('上传完毕.....')
        done();
    }, 2000)
}))


module.exports = {
    clean,
    serve,
    start: serve,
    lint,
    build,
    // deploy
}